package com.my.blog.website.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * <p>文件properties工具类         :<br/></p>
 * <p>description   :<br/></p>
 * <p>
 * created by lijingrun on 2017/10/19.
 */
public class PropertiesUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtils.class);
    private static Properties props;

    static {
        loadProps();
    }

    private synchronized static void loadProps(){
        LOGGER.info("---------------------------------");
        LOGGER.info("开始加载application.properties配置文件");
        props = new Properties();
        InputStream inputStream = null;

        try {
            //inputStream = PropertiesUtils.class.getResourceAsStream("application.properties");
            inputStream = PropertiesUtils.class.getClassLoader().getResourceAsStream("application.properties");
            props.load(inputStream);
        } catch (FileNotFoundException e) {
            LOGGER.error("application.properties文件未找到");
        } catch (IOException e) {
            LOGGER.error("加载properties配置文件，出现IOException");
        } finally {
            try {
                if(null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                LOGGER.error("application.properties文件流关闭出现异常");
            }
        }
        LOGGER.info("加载application.properties配置文件完成");
        LOGGER.info("properties文件内容：\n{}", props);
        LOGGER.info("---------------------------------");
    }

    public static String getProperty(String key){
        if(null == props){
            loadProps();
        }
        return props.getProperty(key);
    }

    public static String getProperty(String key,String defaultValue){
        if (null == props){
            loadProps();
        }
        return props.getProperty(key,defaultValue);
    }
}
